<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\admin\model\order\Loselog;
use app\common\controller\Backend;
use app\common\model\Packages;
use app\common\model\User;
use app\common\model\UserPackagesConfig;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *订单列表
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;
    protected $loselogModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->model        = new \app\admin\model\Order;
        $this->loselogModel = new Loselog();
        $this->view->assign("isCallbackList", $this->model->getIsCallbackList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("isRechargedList", $this->model->getIsRechargedList());
        $this->view->assign("isHexiaoList", $this->model->getIsHexiaoList());
        $this->assignconfig('quanxian', ['ids' => $this->auth->getGroupIds()[0]]);
        $this->view->assign("platformTypeList", $this->model->getPlatformTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $query = $this->model->with(['user', 'packages'])->where($where)->where(['is_agency'=>1]);
            if ($this->auth->getGroupIds()[0] == 4 || $this->auth->getGroupIds()[0] == 6) {
                $query->where(['packages.card_type' => 2]);
            }
            $list = $query->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible([
                    'id',
                    'is_agency',
                    'shipping_contact',
                    'shipping_phone',
                    'shipping_idcard',
                    'shipping_province',
                    'shipping_city',
                    'shipping_area',
                    'shipping_address',
                    'is_callback',
                    'order_id',
                    'phone',
                    'order_status',
                    'rebate',
                    'shipping_company_name',
                    'shipping_no',
                    'is_recharged',
                    'createtime',
                    'callback_time',
                    'audit_status',
                    'platform_type',
                    'image',
                    'audit_upload_time',
                    'admin_image',
                    'is_hexiao',
                    'rebate_recover_msg',
                    'rebate_recover_money',
                    'recover_status',
                    'recover_time',
                    'audit_status',
                    'twoimage',
                    'is_up',
                    'gys'
                ]);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username', 'mobile']);
                $row->visible(['packages']);
                $row->getRelation('packages')->visible(['name', 'card_type', 'pay_channel','supplier']);
            }

            $result = array ("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign("quanxian", $this->auth->getGroupIds()[0]);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!empty($params['baoxiao_status'])) {
            if ($params['baoxiao_status'] == 2) {
                $params['baoxiao_time'] = time();
            }
        }
        $params['is_up'] = 2;
        $params          = $this->preExcludeFields($params);
        $result          = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if (!empty($params['image'])) {
                $params['audit_upload_time'] = time();

            }
            if ($row['order_status'] == 5) {
                $this->error('订单已经结算过了');
            }
            if ($params['order_status'] == 5) {
                $params['settlement_time'] = time();
                orderfencheng($row['id'],$row['goods_id']);
//                $userData                  = findAncestors($row['user_id']);
//                $packageInfo               = Packages::where(['id' => $row['goods_id']])->find();
//                if (!$userData) {
//                    $config = new UserPackagesConfig();
//                    $rebate = $config->where(['user_id'=>$row['user_id'],'packages_id'=>$row['goods_id']])->value('money');
//                    if($rebate){
//                        $packageInfo['rebate']  = $rebate;
//                    }
//                    //顶级代理下单
//                    dingji($row['user_id'], $row['id'], $row['goods_id'], $packageInfo['rebate'], false, true);
//                } else {
//                    array_unshift($userData, $row['user_id']);
//                    $money = moneydigui($row['user_id'], $row['goods_id']);
//                    if ($money) {
//                        digui($row['user_id'], $money, $row['goods_id'], $row['id'], 0, true);
//                    } else {
//                        //顶级
//                        $config = new UserPackagesConfig();
//                        $rebate = $config->where(['user_id'=>$row['user_id'],'packages_id'=>$row['goods_id']])->value('money');
//                        if($rebate){
//                            $packageInfo['rebate']  = $rebate;
//                        }
//                        dingji($row['user_id'], $row['id'], $row['goods_id'], $packageInfo['rebate'], false, true);
//                    }
//                }
            }
            $result = $row->allowField(true)->save($params);

            if (!empty($params['baoxiao_status']) && $result) {
                if ($params['baoxiao_status'] == 2) {
                    $userModel    = new User();
                    $value        = 0;
                    $packagesInfo = \app\admin\model\Packages::where(['id' => $row['goods_id']])->find();
                    if (isset($packagesInfo['epact_set_meal']) && isset($packagesInfo['ciyue_set_meal'])) {
                        $jie_day = date('d');
                        if ($jie_day > 30) {
                            $jie_day = 30;
                        }
                        $value = round((30 - $jie_day) * ($packagesInfo['epact_set_meal'] / 30) + ($packagesInfo['ciyue_set_meal'] * 2),
                            2);
                    }
                    if ($value > 0) {
                        $userModel->money($value, $row['user_id'], '话费报销', $row['id'], $packagesInfo['id']);
                    }

                }
            }

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 审核订单
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if ($row['is_agency'] == 2) {
                $row['image'] = config('site.user_url').$row['image'];
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($params['audit_status'] == 0) {
            $this->error('请选择审核状态');
        }
        if ($params['audit_status'] == 2) {
            $params['baoxiao_status'] = 1;
            if ($row['order_status'] != 5) {
                $params['order_status'] = 4;
            }
        }
        if ($params['audit_status'] == 3 && !$params['reason']) {
            $this->error('请填写驳回原因');
        }
        unset($params['image']);
        $params['audit_time'] = time();
        $params               = $this->preExcludeFields($params);
        $result               = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 佣金追回
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function recover($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if ($row['recover_status'] == 1) {
                $row['rebate_recover_money'] = $row['user_rebate'] * 2;
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['recover_status'] = 2;
        $params['recover_time']   = time();
        $params                   = $this->preExcludeFields($params);
        $result                   = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if ($result) {
                $userModel = new User();
                $userModel->money(-$params['rebate_recover_money'], $row['user_id'],
                    "佣金追回：".$params['rebate_recover_msg'], $row['id'], $row['goods_id']);
            }
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 订单详情
     * @param  null  $ids
     */

    public function orderinfo($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $params['order_id']       = $row['order_id'];
            $params['shipping_phone'] = $row['shipping_phone'];
            $data['appid']            = config('site.ooen_appid');
            $data['timestamp']        = time();
            $data['nonce_str']        = Random::alnum(32);
            $data                     = array_merge($data, $params);
            $string                   = ascll($data);
            $stringSignTemp           = $string.'&appsecret='.config('site.open_appsecret');;
            $data['sign'] = mb_strtoupper(md5($stringSignTemp));
            $url          = "http://agent.haoka.bx10086.cn/v1/haoka_api/orders";//办理套餐
            $res          = httpPost($url, $data);
            $rows         = json_decode($res, true);
            if (empty($rows['rows'][0])) {
                $this->error('未查到信息');
            }
            $this->view->assign('row', $rows['rows'][0]);
            return $this->view->fetch();
        }
    }


    /**
     *  订单处理
     * @param  null  $ids
     */

    public function orderchuli($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign("quanxian", $this->auth->getGroupIds()[0]);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (empty($params['image'])) {
            $this->error('请上传截图');
        }
        if ($row['platform_type'] != 1) {
            $params['baoxiao_status'] = 1;
            if ($row['order_status'] != 5) {
                $params['order_status'] = 4;
            }
        }
        $params['audit_upload_time'] = time();

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 核销
     * @param  null  $ids
     */

    public function hexiao($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params['hexiao_time']    = time();
        $params['hexiao_js_time'] = strtotime($params['hexiao_js_time']);
        $params                   = $this->preExcludeFields($params);
        $result                   = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function importOne($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values['17']) && !empty($values[0])) {
                    $row = $this->model->where(['order_id' => $values[0]])->find();
                    if ($row) {
                        $packageInfo = Packages::where(['id' => $row['goods_id']])->find();
                        if ($packageInfo) {
                            if ($values['17'] == '否') {
                                if (!$row['import_num']) {
                                    if ($row['audit_upload_time']) {
                                        $hexiao_time = date('Y-m-d H:i:s',
                                            86400 * $packageInfo['hexiao_day'] + $row['audit_upload_time']);
                                        if (time() > strtotime($hexiao_time)) {
                                            $row->is_hexiao = 3;

                                        }
                                    }
                                } else {
                                    $row->is_hexiao = 1;
                                }
                                $row->import_num  += 1;
                                $row->hexiao_time = time();
                                $row->save();
                            } elseif ($values['17'] == '是') {
                                $row->is_hexiao = 2;
                                if (!$row['import_num']) {
                                    if ($row['audit_upload_time']) {
                                        $hexiao_time = date('Y-m-d H:i:s',
                                            86400 * $packageInfo['hexiao_day'] + $row['audit_upload_time']);
                                        if (time() > strtotime($hexiao_time)) {
                                            $row->is_hexiao = 3;
                                        }
                                    }
                                }
                                $row->import_num  += 1;
                                $row->hexiao_time = time();
                                $row->save();
                            }
                        }
                    }

                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg,
                $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 订单录入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function importOrder($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                if (count($values) != 9) {
                    $this->error('录入数据结构不对');
                }
                for ($i = 0; $i <= 8; $i++) {
                    if (empty($values[$i])) {
                        $this->error('表格数据缺少必填项');
                    }
                }
//                dump($values);
                //$values[4] 产品id；
                $packagesInfo = \app\admin\model\Packages::where(['id' => $values[4]])->find();

                //$values[2]代理ID
                $UserInfo = \app\admin\model\User::where(['id' => $values[2]])->find();
                if ($packagesInfo && $UserInfo) {
                    if ($packagesInfo['platform_type'] == 1) {
                        $params['id']                = $packagesInfo['packages_id'];
                        $params['shipping_phone']    = $values[0];//办卡人手机号
                        $params['shipping_contact']  = $values[1];//姓名
                        $params['shipping_idcard']   = $values[3];//身份证号
                        $params['shipping_province'] = $values[5];//省
                        $params['shipping_city']     = $values[6];//市
                        $params['shipping_area']     = $values[7];//区
                        $params['shipping_address']  = $values[8];//详情地址
                        $this->orderadd($params, $UserInfo, $packagesInfo);
                    } else {
                        $params['cardType']         = (int)$packagesInfo['packages_id'];
                        $params['provinceName']     = $params['postProvinceName'] = $values[5];       //省
                        $params['cityName']         = $params['postCityName'] = $values[6];           //市
                        $params['postDistrictName'] = $values[7];                                     //区
                        $params['postAddr']         = $values[8];
                        $params['certName']         = $values[1];//姓名
                        $params['certNo']           = $values[3];//身份证号
                        $params['contactNum']       = $values[0];//办卡人手机号
                        $this->orderSync($params, $packagesInfo, $UserInfo);
                    }
                }

            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }

    //平台（platform_type = 2、3、4）
    public function orderSync($params, $info, $UserInfo)
    {
        if ($info['platform_type'] == 4) {
            $this->addorder172($info, $params, $UserInfo, $info['id']);
        } else {
            if ($info['platform_type'] == 3) {
                $params['partnerId'] = config('site.hao3_partnerId');
                $secret              = config('site.hao3_secret');
                $url                 = config('site.site.hao3_url');
            }else{
                $params['partnerId'] = config('site.hao2_partnerId');
                $secret              = config('site.hao2_secret');
                $url                 = config('site.hao2_url');

            }
                $params['number']           = '';
                $params['postProvinceName'] = str_replace('省', '', $params['postProvinceName']);
                $params['provinceName']     = str_replace('省', '', $params['provinceName']);

                if ($params['cityName'] == "市辖区" || $params['cityName'] == "县") {
                    $params['postCityName']     = $params['provinceName'];
                    $params['postProvinceName'] = str_replace('市', '', $params['provinceName']);
                }
                if ($info['province_name']) {
                    $params['provinceName'] = $info['province_name'];
                }
                if ($info['city_name']) {
                    $params['cityName'] = $info['city_name'];//市
                }
                if ($info['is_choose_num'] == 1) {
                    $send['partnerId']    = $params['partnerId'];
                    $send['cardType']     = $info['packages_id'];
                    $send['provinceName'] = $params['provinceName'];
                    $send['cityName']     = $params['cityName'];
                    $send['pageNo']       = 1;
//                    $send['searchValue']  = '';
                    $number               = $this->haoma($send, $url, $secret);
                    if ($number) {
                        $params['number'] = $number;
                    }
                }

                ksort($params);//升序排序
                $str = '';
                foreach ($params as $k => $v) {
                    $str .= $k.$v;
                }
                $str            = $secret.$str.$secret;  //abc123cardType4cityName郑州市pageNo1partnerId1proniceName河南searchValue4150222abc123
                $sign           = strtoupper(md5($str)); //93932E8BD15A2EBE6D0C4F3890B97D90
                $params['sign'] = $sign;
                $url .='/orderSync';
                $res_json       = httpPost($url, $params);
                $res            = json_decode($res_json, true);
                if (!empty($res['data']['orderId'])) {
                    $model = new \app\common\model\Order();
                    $model->orderCreateAdd($params, $UserInfo, $info, $res['data']['orderId']);
                } else {
                    $inser['user_id']     = $UserInfo['id'];
                    $inser['goods_id']    = $info['id'];
                    $inser['message']     = $res['info'];
                    $inser['return_json'] = $res_json;
                    $this->loselogModel->create($inser);
                }
        }
    }



    public function haoma($params, $url, $secret)
    {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k.$v;
        }
        $str            = $secret.$str.$secret;
        $sign           = strtoupper(md5($str));
        $params['sign'] = $sign;
        $url .= '/selectNumber';
        $res            = json_decode(httpPost($url, $params), true);
        if (!empty($res['data']['numArray'])) {
            $res['data']['numArrayTwo'] = [];
            foreach ($res['data']['numArray'] as $k => $v) {
                $res['data']['numArrayTwo'][$k]['id']   = $k + 1;
                $res['data']['numArrayTwo'][$k]['name'] = $v;
            }
            return $res['data']['numArray'][0];
        }
        return false;
    }


    //平台1（platform_type = 1）
    public function orderadd($params, $UserInfo, $packagesInfo)
    {
        $data['appid']     = config('site.ooen_appid');
        $data['timestamp'] = time();
        $data['nonce_str'] = Random::alnum(32);
        $data              = array_merge($data, $params);
        $string            = ascll($data);
        $stringSignTemp    = $string.'&appsecret='.config('site.open_appsecret');;
        $data['sign'] = mb_strtoupper(md5($stringSignTemp));
        $url          = "http://agent.haoka.bx10086.cn/v1/haoka_api/packageOrder";//办理套餐
        $res          = httpPost($url, $data);
        $arr          = json_decode($res, true);
        if (isset($arr['errcode']) && $arr['errcode'] == 0) {
            $user_rebate            = $packagesInfo['rebate'];
            $params['user_id']      = $UserInfo['id'];
            $params['goods_id']     = $packagesInfo['id'];
            $params['order_id']     = $arr['order_id'];
            $params['package_name'] = $packagesInfo['name'];
            $params['parent_id']    = $UserInfo['parent_id'];
            $params['user_rebate']  = $user_rebate;
            unset($params['id']);
            $this->model->create($params);
        } else {
            $inser['user_id']     = $UserInfo['id'];
            $inser['goods_id']    = $packagesInfo['id'];
            $inser['message']     = $arr['errmsg'].$params['shipping_address'];
            $inser['return_json'] = $res;
            $this->loselogModel->create($inser);
        }
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if ($params['daoru_type'] == 1) {
            if ($params['platform_type'] == 2) {
                $this->importtwo($params['image']);
            } else if($params['platform_type'] == 6) {
                $this->kgjimport($params['image']);
            }else if($params['platform_type'] == 7){
                $supplier = \app\admin\model\Packages::where(['id'=>$params['supplier']])->value('supplier');
                $this->zizhuimport($params['image'],$supplier);
            }else if($params['platform_type'] == 8){
                $this->yunlianimport($params['image']);
            }else{
                $this->importOne($params['image']);
            }
        } else {
            $this->importOrder($params['image']);
        }
    }


    //172下单
    public function addorder172($goods, $params, $UserInfo, $goods_id)
    {
        $url                 = config('site.url_172');
        $key                 = config('site.key_172');
        $user_id             = config('site.zhanghao_172');
        $data['user_id']     = $user_id;
        $data['Timestamp']   = time();
        $data['Name']        = $params['certName'];        //姓名
        $data['Phone']       = $params['contactNum'];      //办卡人手机号
        $data['IDCard']      = $params['certNo'];          //身份证号
        $data['Province']    = $params['provinceName'];    //省
        $data['City']        = $params['postCityName'];    //市
        $data['Area']        = $params['postDistrictName'];//区县
        $data['Address']     = $params['postAddr'];        //详细地址
        $data['ProductID']   = $goods['packages_id'];
        $data['DownOrderID'] = 'z'.$this->auth->id.time();
        $data['ThirdPhone']  = '';
        $string              = ascll172($data);
        $data['user_sign']   = strtolower(md5($string.$key));
        $url                 = $url.'/api/order/ApiToOrder';
        $res                 = httpPost($url, $data);
        $arr                 = json_decode($res, true);
        if (!empty($arr['message']) && $arr['code'] == 0) {
            $model = new \app\common\model\Order();
            $model->orderCreateAdd($params, $UserInfo, $goods, $arr['message']);
        } else {
            $inser['user_id']     = $UserInfo['id'];
            $inser['goods_id']    = $goods_id;
            $inser['message']     = $arr['message'];
            $inser['return_json'] = $res;
            $this->loselogModel->create($inser);
        }
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function importtwo($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values[16]) && !empty($values[1])) {
                    $row = $this->model->where(['order_id' => $values[1]])->find();
                    if ($row) {
                        $packageInfo = Packages::where(['id' => $row['goods_id']])->find();
                        if ($packageInfo) {
                            if ($values[16] == '已成功') {
                                $row->is_hexiao = 2;
                                if (!$row['import_num']) {
                                    if ($row['audit_upload_time']) {
                                        $hexiao_time = date('Y-m-d H:i:s',
                                            86400 * $packageInfo['hexiao_day'] + $row['audit_upload_time']);
                                        if (time() > strtotime($hexiao_time)) {
                                            $row->is_hexiao = 3;
                                        }
                                    }
                                }
                                $row->import_num  += 1;
                                $row->hexiao_time = time();
                                $row->save();
                            }
                        }
                    }

                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg,
                $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }


    /**
     * 自助订单导入
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function zizhuimport($file,$supplier)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }

                if (!empty($values[0]) && !empty($values[1]) && !empty($values[2]) && !empty($values[3]) && !empty($values[5])) {
                    $order_status = '1,2,3,4';
                    $orderInfo   = $this->model->where(['order_id'   => $values[1]])->whereIn('order_status', $order_status)->find();
                    $packageInfo = Packages::where(['packages_id' => $values[2],'supplier'=>$supplier])->whereIn('type','1,2')->find();
                    if(!$orderInfo){
                        $where['shipping_contact'] = $values[5];
                        $where['shipping_phone']   = $values[11];
                        $where['goods_id']         = $packageInfo['id']??0;
                        $orderInfo = $this->model->where($where)->whereIn('order_status', $order_status)->find();
                        if(!$orderInfo && $where['goods_id']){
                            $packageInfo = Packages::where(['id'=>['neq',$where['goods_id']],'packages_id' => $values[2],'supplier'=>$supplier])->whereIn('type','1,2')->find();
                            if($packageInfo){
                                $where['goods_id'] = $packageInfo['id'];
                                $orderInfo = $this->model->where($where)->whereIn('order_status', $order_status)->find();
                            }
                        }
                    }
                    if ($orderInfo) {
//                        dump($orderInfo['id']);
                        $v12 = $values[12]??'';//商品描述
//                        if($v13 == "首充" || $v13 == "累充"){
//                            //已首充/待结算/首充
//                            if($v12 == '已首充' || $v12 == '待结算' || $v12 == '首充'){
//                                $orderInfo->order_status    = 4;
//                            }
//                            if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功"){
//                                $orderInfo->order_status    = 1;
//                            }
//                        }
                        if(!empty($values[12])){
                            $orderInfo->remark = $v12;
                        }

//                        if($v13 == "激活"){
//                            if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功" || $v12 == "待结算"){
//                                $orderInfo->order_status    = 4;
//                            }
//                        }
//                        if($v12 == "进行中" || $v12 == "已发货" || $v12 == "发货"){
//                            $orderInfo->order_status    = 2;
//                        }
//                        if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功" || $v12 == "待结算"){
//                            $orderInfo->order_status    = 4;
//                        }

                        if($values[3] == '失败'){
                            $orderInfo->order_status    = 0;
                        }
                        if($values[3] == '进行中'){
                            $orderInfo->order_status    = 2;
                        }
                        if($values[3] == '完成'){
                            $orderInfo->order_status    = 5;
                        }
                        if(!empty($values[17])){
                            $orderInfo->shipping_company_name    = $values[17];
                        }
                        if(!empty($values[18])){
                            $orderInfo->shipping_no    = $values[18];
                        }
                        $orderInfo->import_num += 1;
                        if($orderInfo->order_status == 5){
                            orderfencheng($orderInfo->id,$orderInfo->goods_id);
                        }
                        if(!empty($values[7])){
                            $orderInfo->phone = $values[7];
                        }
//                        $orderInfo->audit_status    = 2;
                        $orderInfo->order_id      = $values[1];
                        $orderInfo->error_msg       = '';
                        $orderInfo->save();
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }

    /**
     * 卡管家导入
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function kgjimport($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        $userModel = new User();
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values[0]) && !empty($values[1]) && !empty($values[4])) {

                    $orderInfo = $this->model->where(['order_id'   => $values[1],'import_num'=>0])->find();
                    if ($orderInfo) {
                        //is_more
                        $orderInfo->import_num += 1;
                        $packageInfo = Packages::where(['id' => $orderInfo['goods_id']])->find();
                        $values[5] = $values[5]??0;
                        $orderInfo->order_status    = 5;
                        $orderInfo->settlement_time = time();
                        $orderInfo->baoxiao_time    = time();
                        $orderInfo->baoxiao_status  = 2;
                        $orderInfo->is_hexiao       = 2;
                        if($orderInfo['is_more'] == 1){
                            if($values[4] && $values[5]){
                                //一次性结算
                                jiesuan($orderInfo,$packageInfo,0);
                            }
                        }else{
                            $orderInfo->is_hexiao       = 5;
                            $orderInfo->baoxiao_status  = 4;
                            jiangli($orderInfo, $packageInfo);
                            if ($orderInfo['parent_id']) {
                                jiangli($orderInfo, $packageInfo, 2);
                            }
                            if ($orderInfo['two_id']) {
                                jiangli($orderInfo, $packageInfo, 3);
                            }
                            //区县
                            if ($orderInfo['agency_area_id']) {
                                jiangli($v, $packageInfo, 4);
                            }
                            //小区
                            if ($orderInfo['plot_id']) {
                                jiangli($orderInfo, $packageInfo, 5);
                            }
                            if($values[5]){
                                $orderInfo->is_hexiao       = 8;
                                $orderInfo->baoxiao_status  = 6;
                                sleep(1);
                                jiangli($orderInfo, $packageInfo,1,2);
                                if ($orderInfo['parent_id']) {
                                    jiangli($orderInfo, $packageInfo, 2,2);
                                }
                                if ($orderInfo['two_id']) {
                                    jiangli($orderInfo, $packageInfo, 3,2);
                                }
                                //区县
                                if ($orderInfo['agency_area_id']) {
                                    jiangli($v, $packageInfo, 4,2);
                                }
                                //小区
                                if ($orderInfo['plot_id']) {
                                    jiangli($orderInfo, $packageInfo, 5,2);
                                }
                            }
                        }
                        if(!empty($values[2])){
                            $orderInfo->phone = $values[2];
                        }
                        $orderInfo->audit_status    = 2;
                        $orderInfo->error_msg       = '';
                        $orderInfo->save();
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }


    /**
     * 云联导入
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function yunlianimport($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        $userModel = new User();
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                dump($values);
                if (!empty($values[13]) && !empty($values[21])) {

                    $orderInfo = $this->model->where(['order_id'   => $values[13],'import_num'=>0])->find();
//                    if ($orderInfo) {
//                        //is_more
//                        $orderInfo->import_num += 1;
//                        $packageInfo = Packages::where(['id' => $orderInfo['goods_id']])->find();
//                        $values[5] = $values[5]??0;
//                        $orderInfo->order_status    = 5;
//                        $orderInfo->settlement_time = time();
//                        $orderInfo->baoxiao_time    = time();
//                        $orderInfo->baoxiao_status  = 2;
//                        $orderInfo->is_hexiao       = 2;
//                        if($orderInfo['is_more'] == 1){
//                            if($values[4] && $values[5]){
//                                //一次性结算
//                                jiesuan($orderInfo,$packageInfo,0);
//                            }
//                        }else{
//                            $orderInfo->is_hexiao       = 5;
//                            $orderInfo->baoxiao_status  = 4;
//                            jiangli($orderInfo, $packageInfo);
//                            if ($orderInfo['parent_id']) {
//                                jiangli($orderInfo, $packageInfo, 2);
//                            }
//                            if ($orderInfo['two_id']) {
//                                jiangli($orderInfo, $packageInfo, 3);
//                            }
//                            //区县
//                            if ($orderInfo['agency_area_id']) {
//                                jiangli($v, $packageInfo, 4);
//                            }
//                            //小区
//                            if ($orderInfo['plot_id']) {
//                                jiangli($orderInfo, $packageInfo, 5);
//                            }
//                            if($values[5]){
//                                $orderInfo->is_hexiao       = 8;
//                                $orderInfo->baoxiao_status  = 6;
//                                sleep(1);
//                                jiangli($orderInfo, $packageInfo,1,2);
//                                if ($orderInfo['parent_id']) {
//                                    jiangli($orderInfo, $packageInfo, 2,2);
//                                }
//                                if ($orderInfo['two_id']) {
//                                    jiangli($orderInfo, $packageInfo, 3,2);
//                                }
//                                //区县
//                                if ($orderInfo['agency_area_id']) {
//                                    jiangli($v, $packageInfo, 4,2);
//                                }
//                                //小区
//                                if ($orderInfo['plot_id']) {
//                                    jiangli($orderInfo, $packageInfo, 5,2);
//                                }
//                            }
//                        }
//                        if(!empty($values[2])){
//                            $orderInfo->phone = $values[2];
//                        }
//                        $orderInfo->audit_status    = 2;
//                        $orderInfo->error_msg       = '';
//                        $orderInfo->save();
//                    }
                }
            }
            exit();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }

}
